package hive.function;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 输入两个参数，一个是字符串，第二个是分隔符
 */
public class Demo02_splitString extends GenericUDTF {

    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {

        List<String> fieldNames = new ArrayList<>();
        List<ObjectInspector> objectInspectors = new ArrayList<>();

        fieldNames.add("index");
        fieldNames.add("lineToWords");
        objectInspectors.add(PrimitiveObjectInspectorFactory.javaIntObjectInspector);
        objectInspectors.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames,objectInspectors);
    }

    @Override
    public void process(Object[] args) throws HiveException {

        List<Object> words = new ArrayList<>();

        //获取第一个参数，被分隔的字符串
        String line = args[0].toString();
        //获取第二个参数，分隔符
        String splitFlag = args[1].toString();

        //字符串按照分隔符进行分割
        String[] fields = line.split(splitFlag);

        int index = 0;

        for (String field : fields) {
            words.clear();
            words.add(index++);
            words.add(field);
            forward(words);
        }

    }

    @Override
    public void close() throws HiveException {

    }
}
